package com.travel.modules.sys.oauth2;

import com.travel.commons.utils.DateUtils;
import com.travel.modules.sys.entity.SysUser;
import com.travel.modules.sys.entity.SysUserToken;
import com.travel.modules.sys.service.ShiroService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Set;

@Component
public class OAuth2Realm extends AuthorizingRealm {
    @Resource
    private ShiroService shiroService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权，在权限验证的时候调用
     * @return info
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SysUser sysUser = (SysUser) principals.getPrimaryPrincipal();
        Integer userId = sysUser.getId();

        Set<String> permsSet = shiroService.getUserPermissions(userId);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证，登录的时候调用
     * @param token token
     * @return 认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();

        /* 根据accessToken查询用户信息 */
        SysUserToken userToken = shiroService.queryByToken(accessToken);
        /* token失效 */
        if (userToken == null || userToken.getExpireTime().getTime() < System.currentTimeMillis()) {
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }

        SysUser user = shiroService.queryUser(userToken.getUserId());

        if (user.getStatus() == 0) {
            throw new LockedAccountException("账号已停用，请联系管理员");
        }

        if (user.getPwLockDate() != null && user.getPwLockDate().after(new Date())) {
            throw new LockedAccountException("账号已被锁定，请在" +
                    DateUtils.format(user.getPwLockDate(), DateUtils.DATE_TIME_PATTERN) + "后登录");
        }

        return new SimpleAuthenticationInfo(user, accessToken, getName());
    }
}
